package net.cohoivang.web;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.interceptor.SessionAware;

import net.cohoivang.user.User;
import net.cohoivang.user.UserManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ActionSupport;

public abstract class GoldenAction extends ActionSupport implements SessionAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static final String SESSION_ID_KEY = "golden_session_key";
	
	protected static final Gson gson = new Gson();
	
	protected String masterBodyTemp = "home.jsp";

	private JsonObject mainJson;
	
	protected static Gson gsonHtml;	
	
	User user;
	
	public void setLanguages(String id) {
		
	}
	
	public User getCurrentUser() {
		return this.user;
	}
	
	public String getCurrentPage() {
		return getCurrentUser().getPage();
	}
	
	public final String getSessionId() {
		return getCurrentUser().sessionId;
	}
	
	public final String getActionJson() {
		String s = gson.toJson(getActionJsonObject());
		return escapeJavaScript(s);
	}
	
	public final JsonObject getActionJsonObject() {
		if (mainJson == null) {
			mainJson = new JsonObject();
			this.fillActionJson(mainJson);
		}
		return mainJson;
	}
	
	protected abstract void fillActionJson(JsonObject mainJson);
	
	private static final Pattern twoBackslashPattern = Pattern.compile("\\\\");
	private static final String twoBackslashInRegex = "\\\\\\\\";
	
	public static String escapeJavaScript(String s) {
		if (s == null) {
			return "";
		}		
		Matcher matcher = twoBackslashPattern.matcher(s);
		s = matcher.replaceAll(twoBackslashInRegex);
		return s;
	}
	
	public void setSession(Map<String, Object> session) {
		String sessionId = (String) session.get(SESSION_ID_KEY);
		User user = UserManager.getInstance().getUser(sessionId);
		if (user == null) {
			user = UserManager.getInstance().createUser();
			session.put(SESSION_ID_KEY, user.sessionId);
		}
	}
	
	protected GoldenAction() {
		if (gsonHtml == null) {
			GsonBuilder builder = new GsonBuilder().disableHtmlEscaping();
			gsonHtml = builder.create();
		}
	}
}
